package cz.spock.cms.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import cz.spock.cms.entity.Node;
import cz.spock.cms.entity.Project;
import cz.spock.cms.service.CmsService;
import cz.spock.cms.service.NodeService;
import cz.spock.cms.service.ProjectService;
import cz.spock.core.controller.BaseController;

/**
 * this controller serves all requests for web pages
 * 
 * TODO some refactoring, error handling
 * 
 * @author miso
 *
 */
@Controller
public class WebController extends BaseController {
    
    @Autowired
    private CmsService cmsService;
    @Autowired
    private ProjectService pService;
    @Autowired
    private NodeService nService;
    
   
    @RequestMapping(value = "/web/{project}/*")
    public void getPage(@PathVariable String project, HttpServletRequest request, HttpServletResponse response) {
        project = "/" + project;
        System.out.println("searching for project "  + project);
        // search for project - dispatched to service class TODO
        Project p = pService.findProjectByUrl(project);
        if(p == null) {
            // TODO project not found - return NOT FOUND PAGE
            System.out.println("Project " + project + " not found.");
            return;
        }
        // search for page - dispatched to service class TODO
        System.out.println("Requested url is: " + request.getRequestURL().toString());
        System.out.println("Requested uri is: " + request.getRequestURI().toString());
        String url = request.getRequestURI().toString();
        url = url.replaceFirst("/spring/web", "");
        System.out.println("searching for page with url "  + url);
        Node n = nService.findNodeByUrl(url);
        if(n == null) {
            // TODO page not found - return NOT FOUND PAGE
            System.out.println("Page not found.");
            return;
        }
        
        // create and send html - dispatched to service class TODO
        nService.getFullDataTree(n); 
        
        try {
            if(response.getOutputStream() == null) {
                System.out.println("WebController.getPage: response.outputStream is null!");
                return;
            }
            cmsService.process(project, url, response.getOutputStream());
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (IOException e) {
            // TODO Auto-generated catch block - return ERROR PAGE
            e.printStackTrace();
        }
    }

}
